package com.shareyi.joywindow;

/*
 * JoyWindow local browser implement(IE[windows],Firefox()) ,this browser is in the swt shell window
 *	and it
 * @since 1.0
 */

import java.util.HashSet;
import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.browser.CloseWindowListener;
import org.eclipse.swt.browser.OpenWindowListener;
import org.eclipse.swt.browser.TitleEvent;
import org.eclipse.swt.browser.TitleListener;
import org.eclipse.swt.browser.WindowEvent;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;

import com.shareyi.joywindow.server.exception.HttpServerException;
import com.shareyi.simpleserver.core.SimpleHttpServer;

public class JoyWindowIE implements JoyWindowIntf{

	Display display;
	Shell shell;
	Browser browser;
	
	private HashSet<String> windowIdSet;
	private static final JoyWindowIE joyWindow=new JoyWindowIE();
	static final String SET_WINDOWID_SCRIPT = "jWindow.setWindowId('testSessionId');";
	private String indexUrl="";
	private WindowConfig config;
	
	private FileDialog saveFileDialog;
	private FileDialog openFileDialog;
	private DirectoryDialog directoryDialog;
	
	
	private JoyWindowIE(){
		windowIdSet=new HashSet<String>();
	}

	public void init() throws Exception
	{
			windowIdSet.add("testSessionId");
			display = new Display();
			Display.setAppName("joyWindow");

			shell = new Shell(display,SWT.MAX|SWT.MIN|SWT.CLOSE); //create window
			shell.setLayout(new FillLayout()); 
			shell.setText("joyWindow");
			makeMenus();
			makeFileDialogs();
			
			shell.setImage(new Image(Display.getDefault(), 
					JoyWindowIE.class.getResourceAsStream("aa.jpg")));
			shell.setSize(900, 560);
			//shell.setModified(false);
			browser= new Browser(shell, SWT.NONE); //create browser
			Menu m1=new Menu(browser);
			MenuItem copyItem=new MenuItem(m1, SWT.POP_UP);
			copyItem.setText("c(复制)");
			copyItem.addSelectionListener(new SelectionListener() {
				
				public void widgetSelected(SelectionEvent arg0) {
					browser.execute("var sText = window.getSelection ? window.getSelection() : document.selection.createRange().text;\n"+
					"if(sText!=null&&sText!='')\nwindow.clipboardData.setData('text',sText);");
				}
				
				public void widgetDefaultSelected(SelectionEvent arg0) {
					// TODO Auto-generated method stub
				}
			});
			
			MenuItem pasteItem=new MenuItem(m1, SWT.POP_UP);
			pasteItem.setText("p(粘贴)");
			pasteItem.addListener(SWT.Selection, new Listener() {
				
				public void handleEvent(Event arg0) {
					browser.execute("var CopiedTxt = document.selection.createRange();\n"+
					"if(document.activeElement.type)\n"+
					"if(CopiedTxt)CopiedTxt.execCommand('paste');");
				}
			});
			
			MenuItem backMenu=new MenuItem(m1, SWT.POP_UP);
			backMenu.setText("向后");
			
			MenuItem forwardMenu=new MenuItem(m1, SWT.POP_UP);
			forwardMenu.setText("向前");
			
			backMenu.addListener(SWT.Selection, new Listener() {
				
				public void handleEvent(Event arg0) {
					browser.back();
				}
			});
			
			forwardMenu.addListener(SWT.Selection, new Listener() {
				
				public void handleEvent(Event arg0) {
					browser.forward();
				}
			});

			browser.setMenu(m1);
		
			
			//弹出新的窗口
			browser.addOpenWindowListener(new OpenWindowListener() {
				
				public void open(WindowEvent event) {
//					if (!event.required) return;	/* only do it if necessary */
					Shell shell = new Shell(display);
				//	shell.setText("New Window");
					shell.setLayout(new FillLayout());
					Browser popbrowser = new Browser(shell,SWT.NONE);
					PopWindowIE.initialize(display, popbrowser);
					((WindowEvent)event).browser = popbrowser;
					
				}
			});
			
			//关闭程序
			browser.addCloseWindowListener(new CloseWindowListener() {		
				public void close(WindowEvent event) {
					shell.dispose();
				}
			});
			
			browser.addTitleListener(new TitleListener() {
				
				public void changed(TitleEvent event) {
					if(event.title!=null&&event.title.trim().length()!=0)
						shell.setText(event.title);
					else shell.setText("joyWindow POWERED");
				}
			});
		
	}
	

	private void makeMenus() {
		// TODO Auto-generated method stub
		Menu menubar=new Menu(shell,SWT.BAR);
		shell.setMenuBar(menubar);
		
		MenuItem ctrlMI=new MenuItem(menubar, SWT.CASCADE);
		ctrlMI.setText("控制");
		Menu ctrlDrpmenu=new Menu(shell,SWT.DROP_DOWN);
		ctrlMI.setMenu(ctrlDrpmenu);
		
		MenuItem refreshMenu=new MenuItem(ctrlDrpmenu, SWT.PUSH);
		refreshMenu.setText("更新界面");
		/*
		MenuItem forwardMenu=new MenuItem(ctrlDrpmenu, SWT.PUSH);
		forwardMenu.setText("上一步");
		MenuItem backwardMenu=new MenuItem(ctrlDrpmenu, SWT.PUSH);
		backwardMenu.setText("");*/
		MenuItem exitMenu=new MenuItem(ctrlDrpmenu, SWT.PUSH);
		exitMenu.setText("退出");

		
		refreshMenu.addListener(SWT.Selection, new Listener() {
			
			public void handleEvent(Event arg0) {
				browser.refresh();
			}
		});
		
		exitMenu.addSelectionListener(new SelectionListener() {
			
			public void widgetSelected(SelectionEvent arg0) {
				shell.dispose();
			}
			
			public void widgetDefaultSelected(SelectionEvent arg0) {
				
			}
		});
		
		
		MenuItem view=new MenuItem(menubar, SWT.CASCADE);
		view.setText("查看");
		Menu view1=new Menu(shell,SWT.DROP_DOWN);
		view.setMenu(view1);
		
		
		
		MenuItem indexMenu=new MenuItem(view1, SWT.PUSH);
		indexMenu.setText("返回主界面");
		
		
		
		MenuItem fullMenu=new MenuItem(view1, SWT.PUSH);
		fullMenu.setText("全屏");
		
		fullMenu.addListener(SWT.Selection,new Listener() {
			
			public void handleEvent(Event arg0) {
				shell.setFullScreen(!shell.getFullScreen());
			}
		});
		

		indexMenu.addListener(SWT.Selection, new Listener() {
			public void handleEvent(Event arg0) {
				browser.setUrl(indexUrl);
			}
		});
	}

	
	/**
	 * 预生成文件选择器
	 */
	/**
	 * 
	 */
	private void makeFileDialogs()
	{
		saveFileDialog=new FileDialog(shell,SWT.SAVE);
		saveFileDialog.setText("保存文件");
		
		
		openFileDialog=new FileDialog(shell,SWT.OPEN);
		openFileDialog.setText("打开文件");
		
		directoryDialog=new DirectoryDialog(shell,SWT.OPEN);
		directoryDialog.setText("选择文件目录");
	}
	
	
	
	
	
	public void openWindow()
	{
		setLocationCenter();
		indexUrl="http://127.0.0.1:"+JoyWindowData.getHttpServer().getPort()+"/";
		browser.setUrl(indexUrl);
		shell.open();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch())
				{
				if(config!=null)
				{
					if(config.getWidth()!=shell.getSize().x||config.getHeight()!=shell.getSize().y)
						shell.setSize(config.getWidth(), config.getHeight());
					if(shell.getAlpha()!=config.getAlpha())
						shell.setAlpha(config.getAlpha());
					setWindowId();
					config=null;
				}	
				display.sleep();
				}
			
		}
		try {
			JoyWindowData.getHttpServer().stop();
		} catch (HttpServerException e) {
			e.printStackTrace();
		}
		System.exit(0);
	}
	
	private void setLocationCenter()
	{
		Rectangle area=Display.getCurrent().getClientArea();
		shell.setLocation(area.width / 2 - shell.getSize().x/2, area.height / 2 - shell.getSize().y/2); 
	}
	
	public boolean checkSessionId(String sessionId) {
		return windowIdSet.contains(sessionId);
	}

	public void closeWindow() {
		
	}

	public void setWindowId()
	{
		browser.execute(SET_WINDOWID_SCRIPT);
	}
	
	
	public static JoyWindowIntf getJoyWindow()
	{
		return joyWindow;
	}

	public void initWindow(WindowConfig config) {
		this.config=config;
	}

	public String chooseFile()
	{
		return indexUrl;
	}
	
	
	public void alertMsg(String msg)
	{
		if(shell!=null)
		{
		MessageBox messageBox = 
			   new MessageBox(shell, 
			     SWT.OK| 
			     SWT.CANCEL| 
			     SWT.ICON_WARNING); 
			messageBox.setMessage(msg);
			messageBox.open();
		}
	}
	
	
	
	String openFilePath;
	boolean openChoosedFlag;

	public synchronized String getOpenPath(final String parentPath,
			final boolean filter, final String[] filterExtensions,
			final String[] filterNames) {
		openChoosedFlag = false;
		Runnable runnable = new Runnable() {

			public void run() {
				if (parentPath != null) {
					openFileDialog.setFilterPath(parentPath);
				}

				if (filter) {
					openFileDialog.setFilterExtensions(filterExtensions);
					openFileDialog.setFilterNames(filterNames);
				} else {
					openFileDialog.setFilterExtensions(new String[] { "*.*" });
					openFileDialog.setFilterNames(new String[] { "*.*" });
				}
				openFilePath = openFileDialog.open();
				openChoosedFlag = true;
			}
		};

		display.asyncExec(runnable);

		while (!openChoosedFlag) {
			try {
				Thread.sleep(60);
			} catch (InterruptedException e) {
			}

		}

		openChoosedFlag = false;
		return openFilePath;
	}

	public synchronized String getOpenPath(final boolean filter,final String[] filterExtensions,final String[] filterNames)
	{
		return getOpenPath(null, filter, filterExtensions, filterNames);
	}

	
	String saveFilePath;
	boolean saveChoosedFlag;
	public synchronized String getSavePath(final boolean filter,final String[] filterExtensions,final String[] filterNames)
	{
		return getSavePath(null, filter, filterExtensions, filterNames);
		
	}
	
	public String getSavePath(final String parentPath,final boolean filter,
			final String[] filterExtensions,final String[] filterNames) {
		saveChoosedFlag=false;
		 Runnable runnable = new Runnable() {

	            public void run() {
	            	if(parentPath!=null){
	            		openFileDialog.setFilterPath(parentPath);
	            	}
	        		if(filter){
	        			saveFileDialog.setFilterExtensions(filterExtensions);
	        			saveFileDialog.setFilterNames(filterNames);
	        		}
	        		else {
	        			saveFileDialog.setFilterExtensions(new String[]{"*.*"});
	        			saveFileDialog.setFilterNames(new String[]{"*.*"});
	        		}
	        		saveFilePath=saveFileDialog.open();
	        		saveChoosedFlag=true;
	            }
	            };

		display.asyncExec(runnable);
		
		while(!saveChoosedFlag)
		{
			try {
				Thread.sleep(60);
			} catch (InterruptedException e) {
			}
		}
		
		saveChoosedFlag=false;
		return saveFilePath;
	}
	
	
	
	String dirFilePath;
	boolean dirChoosedFlag;
	public synchronized String getDirectoryPath(final String path)
	{
		dirChoosedFlag=false;
		 Runnable runnable = new Runnable() {

	            public void run() {
	            	if(path!=null)
	            		directoryDialog.setFilterPath(path);
	            	dirFilePath=directoryDialog.open();
	        		dirChoosedFlag=true;
	            }
	            };

		display.asyncExec(runnable);
		
		while(!dirChoosedFlag)
		{
			try {
				Thread.sleep(60);
			} catch (InterruptedException e) {
			}
		}
		
		dirChoosedFlag=false;
		return dirFilePath;
		
	}


	
}

